John

McDonald's

Project

Cornucopia


A Simple State Machine Example

January 25, 2020

Calculation Tools

In order to learn how to program a state machine I have come up with an example that has four states and four or so transitions. It is hierarchical, has a default state, and uses a selector to switch between two of the states. It is a simple calculator that determines either the primes or fibonacci sequence numbers up to a provided limit. The user enters a limit in a text field, uses a drop down menu to choose either primes or fibonacci sequence numbers, and hits a button to trigger the calculation.

The four states of the finite state machine are "no number entered", "number entered", "prime", and "fibo". The latter two are contained within the "number entered" state. "Prime" is the default state. Nothing is triggered until the "Calculate" button is hit. At that point if there is no number entered, the "no number entered" state becomes active. If a number has been entered, then the "number entered" state becomes active. The "prime" state becomes active by default upon entry into the "number entered" state. If the selector has been used, then either the "prime" or "fibo" state is entered. Entry into either state triggers the calculation and output. One thing I forgot. Every state must have a transition in as well as a transition out. (Though the latter might take place at a higher level in the hierarchy.) So two other transitions for this state machine are clearing the number field upon calculation. Both the "prime" and "fibo" states have this transition back to "no number entered".

State machine chart

Kent Dodds has a write-up at a beginner level on programming a simple finite state machine from scratch. I will use his format to encode the state machine described above. The following is his code for a two state entity.

Beginning of code Middle of code End of code

After a year I am still struggling to understand the above code, so I will attempt to implement a simple state machine just using familiar code. I will start by defining the state machine with an object.